package th.retrofit.lib;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
 * 给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）
 */
public class Solution102 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> results = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> result = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node != null) {
                    result.add(node.val);
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
            }
            if (!result.isEmpty()) {
                results.add(result);
            }
        }
        return results;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,2,3,4,4,3};
        TreeNode[] nodes = new TreeNode[arr.length];
        for (int i = 0; i < arr.length; i++) {
            nodes[i] = new TreeNode(arr[i]);
        }
        TreeNode root = TreeNode.array2Tree(nodes);
        System.out.println(root);
        List<List<Integer>> results = (new Solution102().levelOrder(root));
        results.forEach(it -> {
            for (int i = 0; i < it.size(); i++) {
                System.out.print(it.get(i));
                System.out.print(",");
            }
            System.out.println();
        });
    }

}
